<template>
  <el-button
      type="primary"
      @click="uploadAction"
  >
    <slot></slot>
  </el-button>
</template>

<script lang="ts" setup>
// 上传
import {ElLoading, ElMessage} from "element-plus";
import {FileType, upload} from "@/api/upload";
import {PropType,computed} from "vue";

const props = defineProps({
  type: {
    type: String as PropType<FileType>,
    default: 'image',
  },
});

const accept = computed(() => {
  switch (props.type) {
    case  'image' :
      return '.jpg,.jpeg,.png'
    case  'media' :
      return '.mp4'
    case  'file' :
      return '*'
  }
  return ""
})

interface IEmitsType {
  (e: 'success', obj: { path: string[], images: string[] }): void;
}

const emit = defineEmits<IEmitsType>();

const uploadAction = () => {
  const input = document.createElement('input') as HTMLInputElement
  input.setAttribute('type', 'file')
  input.setAttribute('accept', accept.value)
  input.setAttribute('multiple', 'multiple')
  input.click()
  input.onchange = async () => {
    let index = 0
    const loading = ElLoading.service({
      lock: true,
      text: getText(index, input.files!.length, '1%'),
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const path: string[] = []
    const images: string[] = []
    for (let i = 0; i < input.files!.length; i++) {
      const resp = await upload(props.type, input.files![i], undefined, (progress: any) => {
        // 设置内容
        loading.setText(getText(index, input.files!.length, Math.round(progress.loaded / progress.total * 100) + '%'))
      })
      path.push(resp.path)
      if (resp.image) {
        images.push(resp.image)
      }
      index++
    }
    loading.close()
    emit('success', {path: path, images})
    ElMessage.success(`上传成功!`)
  }

  const getText = (index: number, len: number, text: string): string => {
    if (len === 1) {
      return `正在上传 【${text}】`
    } else {
      return `正在上传 第${index + 1 + ' / ' + len}个， 【${text}】`
    }
  }
}
</script>

<style></style>
